#include "elements/CEGUIDragIcon.h"

namespace CEGUI
{
	const String DragIcon::WidgetTypeName("CEGUI/DragIcon");
	const String DragIcon::EventNamespace("DragIcon");
	const String DragIcon::EventClicked( "Clicked" );
	
	DragIcon::DragIcon(const String& type, const String& name)
		: DragContainer(type, name)
		, d_pushed(false)
		, d_hovering(false)
	{

	}

	DragIcon::~DragIcon(void)
	{

	}

	void DragIcon::updateInternalState(const Point& mouse_pos)
	{
		bool oldstate = d_hovering;

		d_hovering = false;

		const Window* capture_wnd = getCaptureWindow();
		if (capture_wnd == 0)
		{
			System* sys = System::getSingletonPtr();
			if (sys->getWindowContainingMouse() == this && isHit(mouse_pos))
			{
				d_hovering = true;
			}
		}
		else if (capture_wnd == this && isHit(mouse_pos))
		{
			d_hovering = true;
		}

		if (oldstate != d_hovering)
		{
			requestRedraw();
		}

	}

	void DragIcon::onMouseMove(MouseEventArgs& e)
	{
		DragContainer::onMouseMove(e);

		updateInternalState(e.position);
	}

	void DragIcon::onMouseButtonDown(MouseEventArgs& e)
	{
		DragContainer::onMouseButtonDown(e);

		if (e.button == LeftButton)
		{
			d_pushed = true;
			updateInternalState(e.position);
			requestRedraw();
		}

	}

	void DragIcon::onMouseButtonUp(MouseEventArgs& e)
	{
		if ((e.button == LeftButton) && isPushed())
		{
			Window* sheet = System::getSingleton().getGUISheet();

			if (sheet)
			{
				// if mouse was released over this widget
				if (this == sheet->getTargetChildAtPosition(e.position))
				{
					// fire event
					WindowEventArgs args(this);
					onClicked(args);
				}

			}

			e.handled = true;
		}

		DragContainer::onMouseButtonUp(e);
	}

	void DragIcon::onCaptureLost(WindowEventArgs& e)
	{
		DragContainer::onCaptureLost(e);

		d_pushed = false;
		updateInternalState(MouseCursor::getSingletonPtr()->getPosition());
		requestRedraw();
	}

	void DragIcon::onMouseLeaves(MouseEventArgs& e)
	{
		DragContainer::onMouseLeaves(e);

		d_hovering = false;
		requestRedraw();
	}

	void DragIcon::onClicked(WindowEventArgs& e)
	{
		fireEvent(EventClicked, e, EventNamespace);
	}
}